package com.wyl.customui

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.core.widget.addTextChangedListener
import kotlinx.android.synthetic.main.input_number_view.view.*
import kotlin.math.max
import kotlin.math.min

class InputNumberView : FrameLayout {
    var onNumChange: ((Int) -> Unit)? = null
    var max = 0
    var min = 0
    var step = 0
    var count: Int
        set(value) {
//            Log.d("InputNumberView","setCount + $value")
            val str = value.toString()
            et_count.setText(str)
            et_count.setSelection(str.length)
        }
        get() = et_count.text.toString().toInt()

    private var disable: Boolean
        set(value) {
            btn_minus.isEnabled = !value
            btn_plus.isEnabled = !value
        }
        get() = !(btn_minus.isEnabled || btn_plus.isEnabled)

    constructor(context: Context) : super(context) {
        init(null, 0)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(attrs, 0)
    }

    constructor(
        context: Context,
        attrs: AttributeSet,
        defStyle: Int
    ) : super(context, attrs, defStyle) {
        init(attrs, defStyle)
    }

    private fun init(attrs: AttributeSet?, defStyle: Int) {
        LayoutInflater.from(context).inflate(R.layout.input_number_view, this)
        btn_minus.setOnClickListener {
            count = max(count - step, min)
        }
        btn_plus.setOnClickListener {
            count = min(count + step, max)
        }
        et_count.addTextChangedListener {
            Log.d("InputNumberView", it.toString())
            onNumChange?.invoke(it.toString().toInt())
        }

        val ta = context.obtainStyledAttributes(attrs, R.styleable.InputNumberView)
        max = ta.getInt(R.styleable.InputNumberView_max, 100)
        min = ta.getInt(R.styleable.InputNumberView_min, 0)
        step = ta.getInt(R.styleable.InputNumberView_step, 1)
        disable = ta.getBoolean(R.styleable.InputNumberView_disable, false)
        count = ta.getInt(R.styleable.InputNumberView_defaultValue, 0)
        ta.recycle()
    }
}
